package cn.zwt.wolf.task;

import cn.zwt.wolf.constant.GlobleConstant;
import cn.zwt.wolf.convert.BaseInfoConvert;
import cn.zwt.wolf.domain.base.area.Area;
import cn.zwt.wolf.domain.base.language.Language;
import cn.zwt.wolf.domain.base.tag.Tag;
import cn.zwt.wolf.domain.content.Content;
import cn.zwt.wolf.domain.sync.SyncQueue;
import cn.zwt.wolf.domain.program.OrgProgram;
import cn.zwt.wolf.domain.program.SpiderProgram;
import cn.zwt.wolf.service.content.ContentService;
import cn.zwt.wolf.service.sync.SyncQueueService;
import cn.zwt.wolf.service.base.area.AreaService;
import cn.zwt.wolf.service.base.language.LanguageService;
import cn.zwt.wolf.service.base.tag.TagService;
import cn.zwt.wolf.service.program.OrgProgramService;
import cn.zwt.wolf.service.program.SpiderProgramService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by zhangwt on 16-2-28.
 * 定时采集节目信息
 */
@Component
@Lazy(false)
public class CollectProgramTask  {
    Log logger = LogFactory.getLog(CollectProgramTask.class);
    @Inject
    private OrgProgramService orgProgramService;
    @Inject
    private SpiderProgramService spiderProgramService;
    @Inject
    private SyncQueueService syncQueueService;
    @Inject
    private AreaService areaService;
    @Inject
    private LanguageService languageService;
    @Inject
    private TagService tagService;
    @Inject
    private ContentService contentService;

    /**
     *定时任务开始
     */
    @Scheduled(cron="${collectProgramTask}")   //每5秒执行一次
    public void startAutoCollectProgram(){
        logger.info(" ************execute content enter task beginning....************");
        initSyncQueue();
        initOrgProgram();
        initContent();
        logger.info(" **************execute content enter task end************");

    }
    /**
     * 根据syncQueue　选项入库content
     * */
    public void initContent(){
        logger.info("initContent  beginning....");

        Map<String,Object> params= new HashMap<String, Object>(){
            {
                put("status",GlobleConstant.STATUS_NORMAL);
                put("collectStatus",SyncQueue.COLLECT_STATUS_FINISH);
                put("enterStatus",SyncQueue.ENTER_STATUS_INITIAL);
            }
        };
        List<SyncQueue> syncQueues = syncQueueService.findSyncQueuesByStatus(params);
        if (syncQueues.size()>0){
            this.saveOrUpdateContent(syncQueues);
        }
        logger.info("initContent  end....");
    }
    /**
     *
     * */
    public void saveOrUpdateContent(List<SyncQueue> syncQueues){
        logger.info("SyncQueue not enter size is: " + syncQueues.size());
        int count = 1;
        if (syncQueues.size()>0){
            for (SyncQueue syncQueue:syncQueues){
                if (syncQueue!=null){
                    logger.info("content enter title is:"+ syncQueue.getContentName() +" index :"+(count++));
                    Content old_content = contentService.findContentByContentId(syncQueue.getContentId());
                    OrgProgram orgProgram = orgProgramService.findOrgProgramByContentId(syncQueue.getContentId());
                    Content new_content = BaseInfoConvert.convertOrg2Content(orgProgram,old_content);
                    new_content.setDeliveryTime(new Date());
                    contentService.saveOrUpdate(new_content);
                    syncQueue.setEnterStatus(SyncQueue.ENTER_STATUS_FINISH);
                    syncQueue.setUpdateTime(new Date());
                    syncQueue.setEnterTime(new Date());
                    if (syncQueue.getArrangeStatus()==SyncQueue.PUBLISH_ARRANGE_STATUS_FINISH){
                        logger.info("这个属于推荐位");
                        syncQueue.setPositionStatus(SyncQueue.PUBLISH_POSITION_STATUS_INITIAL);
                    }
                    if (syncQueue.getPositionStatus()==SyncQueue.PUBLISH_ARRANGE_STATUS_FINISH){
                        logger.info("这个属于推荐位");
                        syncQueue.setPositionStatus(SyncQueue.PUBLISH_POSITION_STATUS_INITIAL);
                    }
                    if (orgProgram.getMode()==OrgProgram.MODE_AUTO){
                        logger.info("发布");
                        syncQueue.setPublishTime(new Date());
                    }
                    syncQueueService.savaOrUpdate(syncQueue);

                }
            }
        }
    }

    /**
     * 根据syncQueue 的各项状态采集org_program
     *
     * */
    public void initOrgProgram(){
        logger.info("initOrgProgram  beginning....");
        int count = 1;
        Map<String,Object> params= new HashMap<String, Object>(){
            {
                put("status",GlobleConstant.STATUS_NORMAL);
                put("collectStatus",SyncQueue.COLLECT_STATUS_INITIAL);
            }
        };
        List<SyncQueue> syncQueues = syncQueueService.findSyncQueuesByStatus(params);
        if (syncQueues.size()>0){
            for (SyncQueue syncQueue:syncQueues){
                logger.info("index:"+(count++)+" title:"+syncQueue.getContentName());
                saveOrUpdateOrgProgram(syncQueue);
                syncQueue.setCollectStatus(SyncQueue.COLLECT_STATUS_FINISH);
                if (syncQueue.getPositionStatus()==SyncQueue.PUBLISH_POSITION_STATUS_FINISH){//是否是推荐位
                    logger.info("这个属于推荐位");
                    syncQueue.setPositionStatus(SyncQueue.PUBLISH_POSITION_STATUS_INITIAL);
                }
                if (syncQueue.getArrangeStatus()==SyncQueue.PUBLISH_ARRANGE_STATUS_FINISH){
                    logger.info("这个属于编排");
                    syncQueue.setArrangeStatus(SyncQueue.PUBLISH_ARRANGE_STATUS_INITIAL);
                }
                syncQueue.setUpdateTime(new Date());
                syncQueueService.savaOrUpdate(syncQueue);
            }
        }
        logger.info("initOrgProgram  end....");
    }
    /**
     * save orgProgram
     * */
    public void saveOrUpdateOrgProgram(SyncQueue syncQueue){
        logger.info("saveOrUpdateOrgProgram....");
        SpiderProgram spiderProgram = spiderProgramService.findSpiderProgramById(syncQueue.getContentId());
        if (spiderProgram!=null){
            OrgProgram old_orgProgram = orgProgramService.findOrgProgramById(spiderProgram.getId());
            OrgProgram new_orgProgram = BaseInfoConvert.convertSpiderProgram2OrgProgram(spiderProgram, old_orgProgram);
            new_orgProgram.setLanguageCode(getLanguageCode(spiderProgram.getLanguage()));
            new_orgProgram.setAreaCode(getAreaCode(spiderProgram.getArea()));
            new_orgProgram.setTagsCode(getTagCode(spiderProgram.getTags()));
//          new_orgProgram.setRank();
//          new_orgProgram.setRankindex();
            new_orgProgram.setUpdateTime(new Date());
            new_orgProgram.setSid(syncQueue.getContentSid());
            orgProgramService.saveOrUpdateOrgProgram(new_orgProgram);
        }
    }

    /**
     * 获取tag 对应的tag_code
     * */
    public String getTagCode(String names){
        StringBuffer tagCode = new StringBuffer();
        if (names!=null){
            String[] tag_names= names.split("\\|");
            for (String name:tag_names){
                Tag tag = tagService.findTagByName(name);
                if (tag != null)
                    tagCode.append(tag.getCode()+"|");
            }
        }
        return tagCode.toString();
    }
    /**
     * 获取language 对应的language_code
     * */
    public String getLanguageCode(String names){
        String languageCode = "";
        if (names!=null){
            String[] language_names= names.split("/");
            for (String name:language_names){
                Language language = languageService.findLanguageByName(name);
                if (language != null)
                    languageCode += language.getCode()+"|";
            }
        }
        return languageCode;
    }
    /**
     * 获取area 对应的area_code
     * */
    public String getAreaCode(String names){
        String areaCode = "";
        if (names!=null){
           String[] area_names= names.split("/");
            for (String name:area_names){
                Area area = areaService.findAreaByName(name);
                if (area != null)
                    areaCode += area.getCode()+"|";
            }
        }
        return  areaCode;
    }
    /**
     * 将未采集的spiderProgram 加载为syncQueue
     *
     * */
    public void initSyncQueue(){
        logger.info("initSyncQueue  beginning....");
        List<SpiderProgram> spiderPrograms = spiderProgramService.findSpiderProgramsByStatus(SpiderProgram.COLLECT_STATUS_INITIAL);
        logger.info("spiderProgram not colllected size is: " + spiderPrograms.size());
        savaOrUpdateSyncQueue(spiderPrograms);
        logger.info("initSyncQueue  end....");
    }
    public void savaOrUpdateSyncQueue(List<SpiderProgram> spiderPrograms){
        int count = 1;
        for (SpiderProgram spiderProgram:spiderPrograms){
            if (spiderProgram !=null){
                logger.info("save spiderProgram to syncQueue ,title:"+spiderProgram.getTitle()+" index:"+(count++));
                SyncQueue old_syncQueue = syncQueueService.findSyncQueueByContentId(spiderProgram.getId());
                SyncQueue new_syncQueue =BaseInfoConvert.convertSpider2SyncQueue(spiderProgram,old_syncQueue);
                new_syncQueue.setUpdateTime(new Date());
                syncQueueService.savaOrUpdate(new_syncQueue);
                spiderProgram.setCollect_status(SpiderProgram.COLLECT_STATUS_FINISH);
                spiderProgramService.savaOrUpdate(spiderProgram);

            }
        }
    }

}
